# import jedi

# # 创建一个代码分析器
# script = jedi.Script(path='workspace/game_2048/game_2048/flask_server.py')

# # 找到 update_high_score 的所有引用
# # references = script.get_references(line=62, column=31)  # 调整行列号到 update_high_score 的位置
# references = script.get_references(line=10, column=20)  # 调整行列号到 update_high_score 的位置

# print(references)

# # 打印所有相关位置
# for ref in references:
#     print(ref.description)
#     print(ref.full_name)
#     print(f"Found in {ref.module_path}:{ref.line}")
#     print("\n")
#     # # 打印上下文
#     # print(ref.get_definition())

import jedi
import networkx as nx
import matplotlib.pyplot as plt
import os

def analyze_code_structure(project_path):
    # 创建有向图
    G = nx.DiGraph()
    
    # 遍历项目目录下的所有 Python 文件
    for root, _, files in os.walk(project_path):
        for file in files:
            if file.endswith('.py'):
                script_path = os.path.join(root, file)
                
                # 使用 jedi 分析每个文件
                script = jedi.Script(path=script_path)
                
                # 分析所有定义
                for definition in script.get_names():
                    try:
                        name = definition.full_name
                        if name:  # 有些定义可能没有完整名称
                            G.add_node(name)
                            
                            # 获取引用
                            for ref in definition.get_references():
                                if ref.full_name:  # 确保引用也有完整名称
                                    G.add_edge(name, ref.full_name)
                    except Exception as e:
                        print(f"Error processing definition in {script_path}: {e}")
    
    return G

def trace_dependencies(graph, node_name):
    try:
        predecessors = list(graph.predecessors(node_name))
        successors = list(graph.successors(node_name))
        
        print(f"Dependencies for {node_name}:")
        print(f"Called by: {predecessors}")
        print(f"Calls to: {successors}")
    except Exception as e:
        print(f"Error tracing dependencies: {e}")

# 使用示例
project_path = 'workspace/game_2048/game_2048'
print(f"Analyzing project: {project_path}")

graph = analyze_code_structure(project_path)
print(f"Graph has {len(graph.nodes)} nodes and {len(graph.edges)} edges")

# 可视化配置
plt.figure(figsize=(12, 8))
pos = nx.spring_layout(graph, k=1, iterations=50)  # 调整布局参数
nx.draw(graph, pos, 
        with_labels=True,
        node_color='lightblue',
        node_size=2000,
        font_size=8,
        font_weight='bold',
        arrows=True,
        edge_color='gray',
        width=1)

plt.title("Code Dependencies")
# plt.show()

# 如果你想查看特定方法的依赖
method_name = 'game_2048.leaderboard.update_high_score'  # 调整为实际的方法名
trace_dependencies(graph, method_name)
